package com.study.dataStructure.leetcode.stack;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author tiny
 * @date 2021/11/12 17:13
 * @Description: https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
 */
public class Solution {

    public static void main(String[] args) {
        String[] tokens = new String[]{"4","13","5","/","+"} ;
        System.out.println(new Solution().evalRPN(tokens));
    }

    public int evalRPN(String[] tokens) {

        Stack<Integer> numStack = new Stack<Integer>();

        for (String str : tokens) {
            try{
                int num = Integer.parseInt(str);
                numStack.push(num);
            }catch (NumberFormatException e){
                Integer num2 = numStack.pop();
                Integer num1 = numStack.pop();

                numStack.push( cal(str,num1,num2) );
            }
        }

        return numStack.pop();
    }

    private Integer cal(String str, Integer num1, Integer num2) {
        if("+".equals(str)){
            return num1 + num2;
        }else if("-".equals(str)){
            return num1-num2;
        }else if("*".equals(str)){
            return num1 * num2;
        }else if("/".equals(str)){
            return num1 / num2;
        }
        return null;
    }


    class Stack<T> {
        List<T> list = new LinkedList<T>();
        public void push(T t){
            list.add(t);
        }
        public T pop(){
            if(list.size()==0) return null;

            T pop = list.get(list.size()-1);
            list.remove(list.size()-1);
            return pop;
        }
    }



}
